﻿using System;
using System.Drawing;
using WiMo.Games.Drawables;
using System.Drawing.Imaging;

namespace WiMo.Games.OpenGLDisplay.Drawables
{
    public class Rectangle : SpriteShapeBase, ISpriteShape
    {
        public Rectangle()
        {
            ShapeType = ShapeType.Rectangle;
            CollisionShape = CollisionShapes.Rectangle;
        }


        private Bitmap GetRenderImage()
        {
            var bitmap = new Bitmap(Size.Width, Size.Height);
            using (var gr = Graphics.FromImage(bitmap as Bitmap))
            {
                if (FillColor != Color.Transparent)
                    using (var sb = new SolidBrush(FillColor.ToDrawingColor()))
                    {
                        gr.FillRectangle(sb, 0, 0, Size.Width, Size.Height);
                    }

                if (BorderColor != Color.Transparent)
                    using (var pen = new Pen(BorderColor.ToDrawingColor(), Convert.ToSingle(BorderWidth)))
                    {
                        gr.DrawRectangle(pen, 0, 0, Size.Width, Size.Height);
                    }
            }

            return bitmap;
        }

        public override void Render(IDisplay display)
        {
            if (DrawInformation == null)
                DrawInformation = GetRenderImage();

            display.Render(this);
        }

        public override bool CheckForCollision(ISprite sprite)
        {
            return false;
        }


        internal void Render(Graphics graphics, Location displayOffset, WiMo.Games.Rectangle destRect)
        {
            var image =  DrawInformation as Bitmap;
            if (image == null)
                DrawInformation = GetRenderImage();

            var targetRect = BoundingRect.GetIntersection(destRect);
            var srcRect = new WiMo.Games.Rectangle(Math.Max(0, destRect.X - BoundingRect.X), Math.Max(0, destRect.Y - BoundingRect.Y), targetRect.Width, targetRect.Height);

            if (ColorKey == Color.Transparent)
                graphics.DrawImage(DrawInformation as Bitmap, (targetRect + displayOffset).ToDrawingRect(), srcRect.ToDrawingRect(), GraphicsUnit.Pixel);
            else
            {
                var imageAttr = new ImageAttributes();
                imageAttr.SetColorKey(ColorKey.ToDrawingColor(), ColorKey.ToDrawingColor());
                graphics.DrawImage(DrawInformation as Bitmap, (targetRect + displayOffset).ToDrawingRect(), srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, GraphicsUnit.Pixel, imageAttr);
                imageAttr.Dispose();
            }
        }
    }
}
